package com.project.school_flate.serviceimpl.shop;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.shop.ShopExamineDto;
import com.project.school_flate.entity.com.ComAdmin;
import com.project.school_flate.entity.shop.ShopAccount;
import com.project.school_flate.entity.shop.ShopExamine;
import com.project.school_flate.entity.shop.ShopInfo;
import com.project.school_flate.entity.table.shop.ShopExamineTable;
import com.project.school_flate.mapper.shop.ShopAccountMapper;
import com.project.school_flate.mapper.shop.ShopExamineMapper;
import com.project.school_flate.mapper.shop.ShopInfoMapper;
import com.project.school_flate.service.shop.ShopExamineService;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class ShopExamineServiceImpl extends ServiceImpl<ShopExamineMapper, ShopExamine> implements ShopExamineService {

    @Autowired
    private ShopExamineMapper oShopExamineMapper;

    @Autowired
    private ShopInfoMapper oShopInfoMapper;

    @Autowired
    private ShopAccountMapper oShopAccountMapper;

    /**
     * 获取店铺审核
     * @param oShopExamineDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopExamine(ShopExamineDto oShopExamineDto) throws Exception {
        List<ShopExamine> oShopExamineList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oShopExamineDto.getShopId())){
            queryWrapper.where(ShopExamineTable.SHOP_EXAMINE.SHOP_ID.eq(oShopExamineDto.getShopId()));
        }
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oShopExamineDto.getPage() != null && oShopExamineDto.getLimit() != null){
            Page<ShopExamine> ShopExaminePage = oShopExamineMapper.paginateWithRelations(oShopExamineDto.getPage(),oShopExamineDto.getLimit(),queryWrapper);
            oShopExamineList = ShopExaminePage.getRecords();
            total = ShopExaminePage.getTotalRow();
        }else{
            oShopExamineList = oShopExamineMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopExamineList.size();
        }
        //PoToDto
        List<ShopExamineDto> oShopExamineDtoList = (List<ShopExamineDto>) PoToDTO.poToDtoList(oShopExamineList,new ShopExamineDto());
        return Result.ok(oShopExamineDtoList,total);
    }

    /**
     * 添加店铺审核
     * @param oShopExamineDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addShopExamine(ShopExamineDto oShopExamineDto) throws Exception {
        ShopExamine oShopExamine = new ShopExamine();
        PoToDTO.poToDto(oShopExamineDto,oShopExamine);
        //获取登陆店铺账号
        ShopAccount oShopAccount = new ShopAccount();
        if(StpUtil.isLogin()){
            oShopAccount = (ShopAccount) StpUtil.getSession().get("shopAccount");
            if(oShopAccount == null || StringUtils.isBlank(oShopAccount.getId())){
                return Result.error("请先重新登录");
            }
        }else{
            return Result.error("请先重新登录");
        }
        //判断是否是第一次提交审核
        if(StringUtils.isBlank(oShopExamine.getShopId())){
            //添加店铺占位
            ShopInfo oShopInfo = new ShopInfo();
            oShopInfo.setAccountId(oShopAccount.getId());
            oShopInfo.setExamineState(2);
            if(oShopInfoMapper.insert(oShopInfo) == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error("添加店铺审核失败");
            }
            oShopExamine.setShopId(oShopInfo.getId());
        }else{
            UpdateChain.of(ShopInfo.class)
                    .set(ShopInfo::getExamineState, 2)
                    .where(ShopInfo::getId).eq(oShopExamine.getShopId())
                    .update();
        }
        //添加店铺审核
        if(oShopExamineMapper.insert(oShopExamine) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加店铺审核失败");
        }
        return Result.ok("添加店铺审核成功");
    }

    /**
     * 修改店铺审核
     * @param oShopExamineDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateShopExamine(ShopExamineDto oShopExamineDto) throws Exception {
        ShopExamine oShopExamine = new ShopExamine();
        PoToDTO.poToDto(oShopExamineDto,oShopExamine);
        oShopExamine.setAuditTime(new Date());
        //获取登陆管理员
        ComAdmin oComAdmin = new ComAdmin();
        if(StpUtil.isLogin()){
            oComAdmin = (ComAdmin) StpUtil.getSession().get("comAdmin");
            if(oComAdmin == null || StringUtils.isBlank(oComAdmin.getId())){
                return Result.error("请先重新登录");
            }
        }else{
            return Result.error("请先重新登录");
        }
        oShopExamine.setAdminId(oComAdmin.getId());
        if(oShopExamineMapper.update(oShopExamine) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改店铺审核失败");
        }
        //创建店铺
        ShopInfo oShopInfo = new ShopInfo();
        oShopInfo.setId(oShopExamine.getShopId());
        oShopInfo.setExamineState(oShopExamine.getIsPass());
        //判断是否通过
        if(oShopExamine.getIsPass() == 1){
            //修改店铺信息
            oShopInfo.setName(oShopExamine.getName());
            oShopInfo.setAccountId(oShopExamine.getAccountId());
            oShopInfo.setAddress(oShopExamine.getAddress());
            oShopInfo.setMainBusiness(oShopExamine.getMainBusiness());
            oShopInfo.setBusinessLicense(oShopExamine.getBusinessLicense());
            oShopInfo.setOperatePermit(oShopExamine.getOperatePermit());
            oShopInfo.setSchoolId(oShopExamine.getSchoolId());
            oShopInfo.setFullName(oShopExamine.getFullName());
            oShopInfo.setIdCard(oShopExamine.getIdCard());
            oShopInfo.setIdFront(oShopExamine.getIdFront());
            oShopInfo.setIdOpposite(oShopExamine.getIdOpposite());
        }
        //修改店铺状态
        if(oShopInfoMapper.update(oShopInfo) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改店铺审核失败");
        }
        return Result.ok("修改店铺审核成功");
    }

    /**
     * 删除店铺审核
     * @param oShopExamineDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result deleteShopExamine(ShopExamineDto oShopExamineDto) throws Exception {
        ShopExamine oShopExamine = new ShopExamine();
        PoToDTO.poToDto(oShopExamineDto,oShopExamine);
        if(oShopExamineMapper.deleteById(oShopExamine.getId()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除店铺审核失败");
        }
        return Result.ok("删除店铺审核成功");
    }

}
